/*
 * @Author: DUST
 * @Date: 2023-05-29 15:11:48
 * @LastEditors: DUST
 * @LastEditTime: 2023-07-03 16:39:15
 * @FilePath: \koa-node-ts\app\service\NoteServeice.ts
 * @Description:
 * undefined
 */
import { Sequelize } from "sequelize-typescript";
import Notes from "../model/Note";
import { noteItem } from "../validator/NoteValidator";

class NoteServeice {
  /**
   * @description: 查询笔记列表，分页数据
   * @param {number} pageSize：每页最大数据
   * @param {number} pageNumber：当前页码
   */
  getNoteListByPage(pageSize: number, pageNumber: number) {
    return Notes.findAndCountAll({
      raw: true,
      limit: pageSize,
      offset: (pageNumber - 1) * pageSize,
      attributes: [
        "title",
        "id",
        "content",
        "description",
        "star",
        "browseNum",
        "tagIds",
        "createTime",
        "upTime",
        [
          Sequelize.literal(
            "(select nikname from user where user.userId = Notes.userId)"
          ),
          "author",
        ],
      ],
      order: [["createTime", "DESC"]],
    });
  }
  /**
   * @description: 查询笔记列表，分页数据
   * @param {number} pageSize：每页最大数据
   * @param {number} pageNumber：当前页码
   */
  getBrowseNoteListByPage(pageSize: number, pageNumber: number) {
    return Notes.findAndCountAll({
      raw: true,
      limit: pageSize,
      offset: (pageNumber - 1) * pageSize,
      attributes: [
        "title",
        "id",
        // "content",
        "description",
        "star",
        "browseNum",
        "tagIds",
        "createTime",
        "upTime",
        [
          Sequelize.literal(
            "(select nikname from user where user.userId = Notes.userId)"
          ),
          "author",
        ],
      ],
      order: [["createTime", "DESC"]],
    });
  }
  /**
   * @description: 通过主键查询详情数据
   * @param {number} id:主键ID
   */  
  getNoteDetailsByID(id: number) {
    return Notes.findOne({
      where: { id },
      attributes: [
        "title",
        "id",
        "content",
        "description",
        "star",
        "browseNum",
        "tagIds",
        "createTime",
        "upTime",
        [
          Sequelize.literal(
            "(select nikname from user where user.userId = Notes.userId)"
          ),
          "author",
        ],
      ],
    });
  }
  /**
   * @description: 新增一个笔记
   * @param {any} value:要新增的字段
   */
  addNote(value: any) {
    return Notes.create(value);
  }
  updateBrowseNum(id: number, browseNum: number) {
    return Notes.update({ browseNum }, {
      where: {id}
    })
  };
  /**
   * @description: 编辑对应ID的笔记信息
   * @param {noteItem} values：需要修改的字段
   * @param {number} id：需要修改的笔记ID
   */
  editNote(values: noteItem, id: number) {
    return Notes.update(values, {
      where: { id },
    });
  }
  /**
   * @description: 删除笔记
   * @param {number} id：需要删除的笔记的ID
   */  
  deleteNote(id: number) {
    return Notes.destroy({
      where: { id },
    });
  }
}

export default new NoteServeice();
